/**
 * 
 */

(function(){
	var root = this;
	// contenteditor = root.contenteditor;
	var productline = function(productlineId,contenteditor){
		this.id = productlineId;
		this.contenteditor = contenteditor;
		this.changedProperties = {};//临时变量变换集，用于向服务端提交改变的属性值
		this.loadMachineTools();
		this.loadMachineConveyors();
		this.bindClickEvent();
		this.bindDragEvent();
	}



	
	//加载所有机台
	productline.prototype.loadMachineTools = function(){
		this.machines = [];
		var _this = this;
		$.ajax({
			url: '/admin/productline/getMachineTools',
			dataType: 'JSON',
			data: {'pId':_this.id},
			type: 'get',
			async: false,
			success: function(data){
				if (!data.tools) {return};
				$.each(data.tools, function(index,tool){
					var tpl = _this.getToolTpl(tool);
					$('#machine_tools').append(tpl);
				});
			}
		});
	}

	//加载所有链道
	productline.prototype.loadMachineConveyors = function(){
		this.machines = [];
		var _this = this;
		$.ajax({
	        url: '/admin/productline/getMachineConveyors',
	        data: {'pId':_this.id},
	        dataType: 'JSON',
	        type: 'get',
	        async: false,
	        success: function (data) {
	        	if (!data.conveyors) {return};
	            $.each(data.conveyors, function(index,conveyor){
	            	var tpl = _this.getConveyorsTpl(conveyor);
					$('#machine_conveyors').append(tpl);
					// _convertToJson(machine);
					// var newmachine = new mcmachine();
					// copy(machine, newslide);
					// _this.add(newslide);
				});
	        }
	    });
	}

	

	productline.prototype.getToolTpl = function(toolInfo){
		var toolTpl = $('.tpl-tool');
		var content = toolTpl.clone(true);
		content.attr('data-id',toolInfo.id);
		content.attr('id','machine-'+toolInfo.id);
		content.find('.machinename').html(toolInfo.name);
		var imgUrl = getImageUrl(toolInfo.graphic);
		content.find('.imgplus img').attr('src',imgUrl);
		content.find('.machineelem').attr('src',imgUrl);
		content.show();
		// content.show();
        return content.prop('outerHTML');
	}

	

	productline.prototype.getConveyorsTpl = function(conveyorInfo){
		var conveyorTpl = $('.tpl-conveyor');
		var content = conveyorTpl.clone(true);
		content.attr('data-id',conveyorInfo.id);
		content.attr('id','machine-'+conveyorInfo.id);
		content.find('.machinename').html(conveyorInfo.name);
		var imgUrl = getImageUrl(conveyorInfo.graphic);
		content.find('.imgplus img').attr('src',imgUrl);
		content.find('.machineelem').attr('src',imgUrl);
		content.show();
		// content.show();
        return content.prop('outerHTML');
	}




	productline.prototype.bindClickEvent = function(){
		var _this = this;
		$('#page-elements').find('.bluetpl_panel').on('click', function(e){
            var targetElem = $(this).find('.elem-wrap');
            machineId = $(this).attr('data-id');
            var newId = _this.id+'_'+machineId;
            _this.contenteditor.renderElem(targetElem,_this.id,machineId);
            _this.contenteditor.setPosition($('#'+newId));
            e.stopPropagation();
            e.preventDefault();
        });
	}

	productline.prototype.bindDragEvent = function(){
		var elems = $('#page-elements').find('.bluetpl_panel');

        for(var i=0;i<elems.length;i++){

            elems[i].ondragstart = function(ev){ //拖拽前触发

              // this.style.background = 'yellow';
              elemId = $(this).attr('id');
              ev.dataTransfer.setData('elemId',elemId);  //存储一个键值对 : value值必须是字符串
              
              // ev.dataTransfer.effectAllowed = 'link';
              
              // ev.dataTransfer.setDragImage(this,0,0);

            };

            elems[i].ondragend = function(){  //拖拽结束触发
            	elemId = $(this).attr('id');
            	$('#page-elements').find('#'+elemId).hide();
            	// alert(elemId);
                this.style.background = '';

            };
        }
	}





	function getImageUrl(graphic){
		var baseUrl = $('#imgurl').val();
		var reg=/__IMAGEURL__/g;
		return baseUrl.replace(reg,graphic);
	}




	productline.prototype.setChangedProperty = function(key,value){
		this.changedProperties [key] = value;
	}

	
	productline.prototype.saveChangedProperties = function (){
		
		if(helpers.isEmptyObject(this.changedProperties)){
			return;
		}
		console.log(this.changedProperties);
		var properties = "";
		each(this.changedProperties,function($value,$key){
			//$value = encodeURIComponent($value);
			properties += $key+"="+JSON.stringify($value)+"&";// [$key] = $value
		});
		
		var mcid = this.id;
					
		$.ajax({
			url: "/productline/savemcProperties",
			data: "id=" + mcid+"&"+properties,
			dataType: "json",
			type: "POST",
			async: false,
			timeout: 10000,
			success: function(data){
				if(data)
				{
					console.log(data);
				}
			},
		});
	}


	
	function _convertToJson(slideData){
		slideData.id = parseInt(slideData.id);
		slideData.sn = parseInt(slideData.sn);
		slideData.name = slideData.name;
		if(slideData.background){
			if(slideData.background === "none")
				{
					slideData.background = "none"
				}
			else{
				slideData.background = JSON.parse(slideData.background);
			}
		}
		if(slideData.bgm){
			slideData.bgm = JSON.parse(slideData.bgm);
		}
		if(slideData.animframes){
			slideData.animframes = JSON.parse(slideData.animframes);
		}
		if(slideData.speech){
			slideData.speech = JSON.parse(slideData.speech);
		}
		if(slideData.timeline){
			slideData.timeline = JSON.parse(slideData.timeline);
		}
		if(slideData.timeDelta){
			slideData.timeDelta = parseFloat(slideData.timeDelta);
		}
		if(slideData.content){
			slideData.content = helpers.decodeHTML(slideData.content);
		}
		
		return slideData;
	}

	root.productline = productline;
	
}).call(this);